<template>
  <div class="publish-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>发布文章</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <el-form ref="form" :model="article" label-width="80px" :rules="formRules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="article.title"></el-input>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-tiptap
          v-model="article.content"
          :extensions="extensions"
          height="400"
          placeholder="请输入文章内容"
        ></el-tiptap>
        </el-form-item>

        <el-form-item label="封面">
          <el-radio-group v-model="article.cover.type" @change="coverTypeChangeAction">
            <el-radio :label="1">单图</el-radio>
            <el-radio :label="3">三图</el-radio>
            <el-radio :label="0">无图</el-radio>
            <el-radio :label="-1">自动</el-radio>
          </el-radio-group>
          <div class="cover-container" v-if="article.cover.type > 0">
              <cover-img v-for="(cover,index) in article.cover.type" v-model="article.cover.images[index]"  :key="cover" @imgTap="addCoverImg"/>
          </div>
        </el-form-item>

        <el-form-item label="频道" prop="channel_id">
          <el-select v-model="article.channel_id" placeholder="请选择频道">
            <el-option
              v-for="item in channels"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button @click="onPublish(true)">存为草稿</el-button>
          <el-button type="primary" @click="onPublish()">发表</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <choose-img ref="chooseImg" :maxCount="article.cover.type" @confirm="chooseImgAction"></choose-img>

  </div>
</template>

<script>
import {
  getArticleChannels,
  addArticle,
  getArticleDetail,
  updateArticleDetail
} from '@/api/article'
import _ from 'lodash'
import {
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  Image,
  TodoItem,
  TodoList,
  FontSize,
  Preview,
  Fullscreen,
  CodeBlock,
  TextColor
} from 'element-tiptap'
import 'element-tiptap/lib/index.css'
import { uploadImage } from '@/api/image'
import CoverImg from './components/cover-img.vue'
import ChooseImg from './components/choose-img.vue'
export default {
  name: 'PublishIndex',
  data () {
    return {
      article: {
        title: '',
        content: '',
        cover: {
          type: 0, // 封面类型 -1:自动，0-无图，1-1张，3-3张
          images: []
        },
        channel_id: ''
      },
      channels: [],
      extensions: [
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 5 }),
        new Bold({ bubble: true }), // render command-button in bubble menu.
        new Underline({ bubble: true, menubar: false }), // render command-button in bubble menu but not in menubar.
        new Italic(),
        new Strike(),
        new ListItem(),
        new BulletList(),
        new OrderedList(),
        new Image({
          uploadRequest (file) {
            const fd = new FormData()
            fd.append('image', file)
            return uploadImage(fd).then(res => {
              return res.data.data.url
            })
          }
        }),
        new TodoItem(),
        new TodoList(),
        new FontSize(),
        new Preview(),
        new Fullscreen(),
        new CodeBlock(),
        new TextColor()
      ],
      formRules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' },
          { min: 5, max: 30, message: '长度在5～30之间', trigger: 'blur' }
        ],
        content: [
          {
            validator: (rule, value, callback) => {
              if (value === '<p> </p>') {
                callback(new Error('文章内容不能为空'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          },
          { required: true, message: '文章内容不能为空', trigger: 'blur' }
        ],
        channel_id: [
          { required: true, message: '频道不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  props: {},
  components: {
    'el-tiptap': ElementTiptap,
    'cover-img': CoverImg,
    'choose-img': ChooseImg
  },
  mounted () {},
  created (e) {
    this.loadArticleChannels()
    if (this.$route.query.id) {
      this.loadArticleDetail()
    }
  },
  methods: {
    onPublish (draft = false) {
      // 获取表单校验结果
      this.$refs.form.validate((valid, err) => {
        if (!valid) {
          return
        }
        if (this.$route.query.id) {
          updateArticleDetail(this.$route.query.id, this.article, draft)
            .then((res) => {
              this.$message({
                message: '更新成功',
                type: 'success'
              })
            })
            .catch((e) => {})
        } else {
          addArticle(this.article, draft)
            .then((res) => {
              this.$message({
                message: `${draft ? '存入草稿' : '发表'}成功`,
                type: 'success'
              })
            })
            .catch((e) => {})
        }
      })
    },
    // 加载文章频道
    loadArticleChannels () {
      getArticleChannels()
        .then((res) => {
          this.channels = res.data.data.channels
        })
        .catch((e) => {})
    },
    // 加载文章内容
    loadArticleDetail () {
      getArticleDetail(this.$route.query.id)
        .then((res) => {
          this.article = res.data.data
        })
        .catch((e) => {})
    },
    // 更新指定文章
    updateArticleDetail () {
      updateArticleDetail()
        .then((res) => {})
        .catch((e) => {})
    },
    // 添加图片
    addCoverImg () {
      this.$refs.chooseImg.open()
    },

    chooseImgAction (data) {
      this.article.cover.images = _.cloneDeep(data)
    },
    // 封面类型选择
    coverTypeChangeAction () {
      this.article.cover.images = []
    }

  }
}
</script>

<style lang="less" scoped>
.cover-container {
  display: flex;
  flex-direction: row;
  align-items: center;
}
</style>
